﻿using Dapper;
using Dapper.Contrib.Extensions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace PuvBuilder
{

    public class PuvBuilder
    {
        public static int DaysInterval = 1;
        static readonly string TaskQuerySql = " select * from iSchoolArticle.dbo.PuvTask where IsValid=1 and IsEnable=1 ";
        static readonly string FilterQuerySql = " select * from iSchoolArticle.dbo.PuvFilter where IsValid=1 ";

        public static void Run()
        {
            using var connDef = PuvDbHelper.GetDbConnection();
            var tasks = connDef.Query<PuvTask>(TaskQuerySql);
            var filters = connDef.Query<PuvFilter>(FilterQuerySql);


            //逐次执行每个任务
            foreach (var task in tasks)
            {
                var taskName = task.Name;
                var connQuery = PuvDbHelper.GetDbConnection(task.ConnectionStr);
                var taskFilters = filters.Where(s => s.Name == taskName).OrderByDescending(s => s.Sort);

                var currentExecuteTime = DateTime.Now;
                //最近一次查询距离现在多久
                var diffDays = (currentExecuteTime.Date - task.LastExecuteTime.Date).Days;

                //如果间隔时间超出30天, 则分开查询
                for (int i = 0; i < diffDays; i += DaysInterval)
                {
                    var partStartTime = task.LastExecuteTime.Date.AddDays(i);
                    var partEndTime = partStartTime.AddDays(DaysInterval);
                    //今日未过完, 不能查当天的数据
                    partEndTime = partEndTime > DateTime.Today ? DateTime.Today : partEndTime;

                    var data = GetData(connQuery, task.Sql, partStartTime, partEndTime).ToList();
                    HandleData(taskFilters, taskName, ref data);

                    //add items
                    connDef.Insert(data);
                    //conn.InsertBulk(data);
                }

                //add log
                var log = new PuvTaskLog()
                {
                    Name = taskName,
                    ExecuteTime = currentExecuteTime,
                    IsSucceed = true
                };
                connDef.Insert(log);

                //update config
                task.LastExecuteTime = currentExecuteTime;
                connDef.Update(task);
            }
        }

        private static void HandleData(IEnumerable<PuvFilter> filters, string taskName, ref List<PuvItem> data)
        {
            var hasFilter = filters.Any();
            data.AsParallel().ForAll(item =>
            {
                item.Name = taskName;
                item.KeyCode = string.Empty;

                if (hasFilter)
                {
                    foreach (var filter in filters)
                    {
                        if (Regex.IsMatch(item.Url, filter.UrlRegex))
                        {
                            item.KeyCode = filter.KeyCode;
                            break;
                        }
                    }
                }
            });
        }

        public static IEnumerable<PuvItem> GetData(IDbConnection conn, string sql, DateTime startTime, DateTime endTime)
        {
            if (startTime == endTime)
            {
                return Enumerable.Empty<PuvItem>();
            }
            return conn.Query<PuvItem>(sql, new { startTime, endTime });
            //return GetTestData();
        }


        private IEnumerable<PuvFilter> GetTestFilter()
        {
            return new List<PuvFilter>()
            {
                //https://m3.sxkid.com/school_detail_wechat/eid=092D223A-5D02-48FF-AE04-FD1C9683EB5D
                //https://m3.sxkid.com/school_detail_wechat/data/eid=092D223A-5D02-48FF-AE04-FD1C9683EB5D_type=1
                new PuvFilter(){ Name = "Task1", UrlRegex = "^https://m.?\\.sxkid.com/school_detail_wechat/", KeyCode = "WeChatSchool"},
                
                //https://m.sxkid.com/school/wechat/vnzfa
                //https://m.sxkid.com/school/wechat/detail/vnzfa_type=1
                new PuvFilter(){ Name = "Task1", UrlRegex = "^https://m.?\\.sxkid.com/school/wechat/", KeyCode = "WeChatSchool"},
            };
        }

        public IEnumerable<PuvItem> GetTestData()
        {
            var random = new Random();
            for (int i = 0; i < 10; i++)
            {
                var t = i % 3;

                var url = "https://m.sxkid.com/school_detail_wechat/" + i;
                if (t == 0)
                {
                    url = "https://m.sxkid.com/school/wechat/" + i;
                }
                else if (t == 1)
                {
                    url = "https://m.sxkid.com/test" + i;
                }
                yield return new PuvItem()
                {
                    Url = url,
                    KeyCode = null,
                    ViewDate = DateTime.Now.AddDays(-random.Next(i)),
                    Pv = i + random.Next(i),
                    Uv = i
                };
            }
        }
    }


}
